# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jhkim

import getpass
import os
import datetime
from absl import app
import pandas
from google.protobuf.json_format import MessageToDict

from coin.base.query_util import query_pta
from xunkemgmt_client.client.util.query_util import (
  query_accounts, get_account_id_from_request, query_position_snapshots)


def get_position_data(request_list):
  results = []
  account_ids = get_account_id_from_request(request_list)
  results = query_position_snapshots(account_ids=account_ids, as_proto=True)
  return results


def get_key_file(exchange, market_type, account):
  root_path = os.path.expanduser(f"/home/{getpass.getuser()}/workspace/coin_key_high/trade")
  if exchange == "Okex" and market_type == "Futures":
    return f"{account}/OKEx/trade_v5_key.json"
  elif exchange == "Huobi" and market_type == "Futures":
    return f"{account}/Huobi/fut_trade_key.json"
  # raise ValueError((exchange, market_type, account))


def get_cmd_clear(exchange, market_type, account, symbol, strategy_name):
  key_path = get_key_file(exchange, market_type, account)
  # assert os.path.exists(key_path), key_path
  api = "v5" if exchange == "Okex" else "v1"
  if exchange == "Huobi":
    recipe = "bbo"
  else:
    recipe = "realtime"

  local_key_path = f"clear_scripts/{exchange}_{account}.txt"
  cmd_pre = f"""./python/coin_deploy/fab.sh \
-f python/coin_deploy/fabhelper/fabutil.py \
-P upload_coin_key_high:vault_token_file="./python/coin_deploy/vault/coin_key_high.json",\
key_name="trade/{key_path}",\
remote_key_path="{local_key_path}",\
run_local=True\n"""

  cmd = (
      f"GLOG_logtostderr=1 ../coin_binary/coin2-bazel-bin/cc/appcoin2/support/approach_target_position "
      f"--mea={market_type}.{exchange}.{api}.{recipe} "
      f"--hard_close "
      f"--key_path={local_key_path} "
      f"--symbol={symbol} --target_position=0 --stickiness=2 "
      f"--lot_size={100 if 'BTC' in symbol else 200 } "
      f" --pass_bp=0 |& tee log_clear/{exchange}_{market_type}_{account}_{symbol}.txt &")
  return cmd_pre + cmd


def main(_):
  current_time = datetime.datetime.utcnow()
  yesterday = current_time.date() - datetime.timedelta(days=1)
  stratdf = query_pta(yesterday,
                       yesterday + datetime.timedelta(days=1),
                       business_units=['Coin'])
  stratdf = stratdf[['strategy_name', 'account_id', 'owner', 'trader', 'market_type']]

  coin_request_list = query_accounts(business_units=['Coin'], active=True, as_proto=True)
  received_data = get_position_data(coin_request_list)
  rows = []
  for record in received_data:
    for each_position in record.each_position:
      if hasattr(each_position, 'long_position'):
        if each_position.long_position > 0 or each_position.short_position > 0:
          out_dict = MessageToDict(each_position, preserving_proto_field_name=True)
          out_dict['account_id'] = record.position_info.account_id
          out_dict['exchange'] = record.position_info.exchange
          rows.append(out_dict)

  df = pandas.DataFrame(rows)

  combdf = df.merge(stratdf, on='account_id', how='inner')

  os.makedirs("clear_scripts", exist_ok=True)
  for trader, trddf in combdf.groupby('trader'):
    with open(f"clear_scripts/clear_{trader}.txt", "w") as out_sh:
      print("mkdir -p log_clear", file=out_sh)
      for accid, accdf in trddf.groupby('account_id'):
        first_row = accdf.iloc[0]
        for rolling, rolled in [
            ('20211231', '20211224'),
            ('20220325', '20211231')]:
          # if week/next week doesnt exist, let it go.
          if first_row['exchange'] in ["Binance", "Ftx"]:
            continue
          exist_rolling_symbols = accdf['symbol'][accdf['symbol'].str.find(rolling) >= 0]
          exist_rolled_symbols = accdf['symbol'][accdf['symbol'].str.find(rolled) >= 0]
          will_be_rolled_symbols = exist_rolling_symbols.str.replace(rolling, rolled)

          dangling_symbols = set(will_be_rolled_symbols) - set(exist_rolled_symbols)
          if len(dangling_symbols) > 0:
            print("\n", file=out_sh)
            print(
                f"# {first_row['strategy_name']} {first_row['exchange']} "
                f"{first_row['market_type']} {first_row['owner']}", file=out_sh)
            for dangling_symbol in dangling_symbols:
              dangling_symbol = dangling_symbol.replace(rolled, rolling)
              print(get_cmd_clear(
                  first_row['exchange'],
                  first_row['market_type'],
                  first_row['owner'],
                  dangling_symbol,
                  first_row['strategy_name']), file=out_sh)
      print("wait", file=out_sh)


if __name__ == '__main__':
  app.run(main)
